<?php
/**
 * 邀请返利API逻辑层
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\api\logic;

use app\common\logic\Invite as CommonInvite;

class Invite extends ApiBase
{
    
    public static $commonInviteLogic = null;
    
    /**
     * 基类初始化
     */
    public function __construct()
    {
        // 执行父类构造方法
        parent::__construct();
        
        empty(static::$commonInviteLogic) && static::$commonInviteLogic = new CommonInvite();
    }

    /**
     * 生成邀请码
     */
    public function generateInviteCode($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        $result = static::$commonInviteLogic->generateInviteCode($data);
        
        // 操作方法：处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0]) && $result[0] == RESULT_SUCCESS) {
            return $result[2]; // 返回数据部分
        } else {
            throw new \Exception($result[1] ?? '生成邀请码失败');
        }
    }
    
    /**
     * 处理邀请关系
     */
    public function processInviteRelation($data = [])
    {
        // JWT解析获取user_id作为被邀请人
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['invitee_id'] = $userData['user_id'];
        }
        
        $result = static::$commonInviteLogic->processInviteRelation($data);
        
        // 返回风格参考 Favorite.php：统一返回 code/msg
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return [API_CODE_NAME => 0, API_MSG_NAME => '操作成功'];
            } else {
                return [API_CODE_NAME => -1, API_MSG_NAME => ($result[1] ?? '操作失败')];
            }
        }
        
        return [API_CODE_NAME => -1, API_MSG_NAME => '操作失败'];
    }
    
    /**
     * 获取邀请统计
     */
    public function getUserInviteStats($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        $result = static::$commonInviteLogic->getUserInviteStats($data);
        
        // 查询方法：直接返回数据
        return $result[0] == RESULT_SUCCESS ? $result[2] : [];
    }
    
    /**
     * 获取用户余额
     */
    public function getUserBalance($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        $result = static::$commonInviteLogic->getUserBalance($data);
        
        // 查询方法：直接返回数据
        return $result;
    }
    
    /**
     * 获取邀请列表
     * @author 王勇程 <laughskydragon@qq.com>
     * @param array $data
     * @return array
     */
    public function getInviteList($data = [])
    {
        // 1. JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }

        // 2. 调用getWhere方法
        $where = static::$commonInviteLogic->getWhere($data);

        // 3. 调用common层业务逻辑
        $result = static::$commonInviteLogic->getInviteList($where);

        return $result[0] == RESULT_SUCCESS ? $result[2] : [];
    }
    
    /**
     * 获取佣金记录
     * @author 王勇程 <laughskydragon@qq.com>
     * @param array $data
     * @return array
     */
    public function getCommissionLog($data = [])
    {
        // 1. JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }

        // 2. 调用getWhere方法
        $where = static::$commonInviteLogic->getWhere($data);

        // 3. 调用common层业务逻辑
        $result = static::$commonInviteLogic->getCommissionLog($where);

        return $result[0] == RESULT_SUCCESS ? $result[2] : [];
    }

    /**
     * 获取最近邀请佣金用户（广告）
     */
    public function getRecentCommissionUsers($data = [])
    {
        // 不需要用户身份，允许公开展示
        $limit = isset($data['limit']) ? intval($data['limit']) : 20;
        $data['limit'] = $limit;
        $result = static::$commonInviteLogic->getRecentCommissionUsers($data);
        return $result;
    }
    
    /**
     * 申请提现
     */
    public function applyWithdraw($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        $result = static::$commonInviteLogic->applyWithdraw($data);
        
        // 操作方法：处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0]) && $result[0] == RESULT_SUCCESS) {
            return $result[2]; // 返回数据部分
        } else {
            throw new \Exception($result[1] ?? '申请提现失败');
        }
    }
    
    /**
     * 获取提现记录
     */
    public function getWithdrawLog($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        $result = static::$commonInviteLogic->getWithdrawLog($data);
        
        // 查询方法：直接返回数据
        return $result;
    }
    
    /**
     * 获取邀请规则
     */
    public function getInviteRules($data = [])
    {
        $result = static::$commonInviteLogic->getInviteRules($data);
        
        // 查询方法：直接返回数据
        return $result;
    }
    
    /**
     * 生成邀请二维码
     */
    public function generateQrcode($data = [])
    {
        try {
            // JWT解析获取user_id
            $token = $data['user_token'] ?? '';
            if (!empty($token)) {
                $userData = get_user_by_token($token);
                $data['user_id'] = $userData['user_id'];
            }

            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                throw new \Exception('用户ID不能为空');
            }

            // 使用邀请人ID作为scene，避免重复码与生成复杂度
            $inviteeScene = 'inviter_id=' . strval($userId);

            // 目标保存路径与文件名（固定命名，避免重复生成）
            $saveDir = PATH_UPLOAD . 'extend' . DS . 'qrcode' . DS;
            if (!is_dir($saveDir)) { @mkdir($saveDir, 0777, true); }
            $fileName = 'mp_uid_' . $userId . '.png';
            $fullPath = $saveDir . $fileName;

            // 同步生成或获取邀请码（与用户ID强相关）
            $codeResult = static::$commonInviteLogic->generateInviteCode(['user_id' => $userId]);
            if ($codeResult[0] != RESULT_SUCCESS) {
                throw new \Exception($codeResult[1] ?? '获取邀请码失败');
            }
            $inviteCode = $codeResult[2]['invite_code'];
            
            // 已存在则直接返回
            if (file_exists($fullPath)) {
                return [
                    'inviter_id' => $userId,
                    'invite_code' => $inviteCode,
                    'qrcode_url' => '/upload/extend/qrcode/' . $fileName,
                    'qrcode_path' => $fullPath
                ];
            }

            // 获取微信access_token
            $appid = config('wechat.appid');
            $secret = config('wechat.secret');
            if (empty($appid) || empty($secret)) {
                throw new \Exception('微信配置缺失');
            }

            $tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
            $tokenResp = $this->httpGetRaw($tokenUrl);
            $tokenJson = json_decode($tokenResp, true);
            $accessToken = $tokenJson['access_token'] ?? '';
            if (empty($accessToken)) {
                $msg = $tokenJson['errmsg'] ?? 'access_token获取失败';
                throw new \Exception($msg);
            }

            // 生成不限制小程序码（永久有效）
            $qrUrl = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $accessToken;
            $payload = [
                'scene' => $inviteeScene,
                'page' => 'pages/index/index',
                'width' => 430,
                'check_path' => false,
                'env_version' => 'release',
                'is_hyaline' => false
            ];
            $qrResp = $this->httpPostJson($qrUrl, json_encode($payload, JSON_UNESCAPED_UNICODE));

            // 成功将返回二进制图片，失败返回JSON
            $tryJson = json_decode($qrResp, true);
            if (is_array($tryJson) && isset($tryJson['errcode']) && $tryJson['errcode'] != 0) {
                $errmsg = $tryJson['errmsg'] ?? '生成小程序码失败';
                throw new \Exception($errmsg);
            }

            // 保存图片到文件
            $fp = fopen($fullPath, 'wb');
            if ($fp === false) { throw new \Exception('文件保存失败'); }
            fwrite($fp, $qrResp);
            fclose($fp);

            return [
                'inviter_id' => $userId,
                'invite_code' => $inviteCode,
                'qrcode_url' => '/upload/extend/qrcode/' . $fileName,
                'qrcode_path' => $fullPath
            ];
        } catch (\Throwable $e) {
            throw new \Exception('生成邀请小程序码失败：' . $e->getMessage());
        }
    }
    
    /**
     * 生成二维码图片
     */
    private function generateQrcodeImage($content)
    {
        // 已由 generateQrcode 统一处理，这里不再使用
        return '';
    }

    private function httpGetRaw($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    private function httpPostJson($url, $jsonBody)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonBody);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
